import { Service } from 'egg';

interface shopType {
  id: number
  signature: string
  name: string
}

export default class ShopService extends Service {
  public async create(options) {
    const { app, ctx } = this;
    const { name } = options;
    const shop = await app.mysql.select('shops', { where: { name } });
    if (shop.length !== 0) return { status: 400, err: '店铺名已存在，请重新命名！' };
    await app.mysql.insert('shops', {
      name,
      createAt: ctx.helper.getCreateAt(),
      updateAt: ctx.helper.getCreateAt(),
    });
    return { message: '创建成功！' };
  }

  public async update(shopId, options) {
    const { app } = this;
    const currentShop = await app.mysql.select('shops', { where: { id: shopId } });
    if (currentShop.length === 0) return { status: 400, err: '店铺不存在' };
    const data = {
      id: (currentShop[0] as shopType).id,
      ...options,
    };
    await app.mysql.update('shops', data);
    return { message: '更新成功！' };
  }

  public async getShopById(shopId) {
    const { app } = this;
    const shops = await app.mysql.select('shops', { where: { id: shopId } });
    if (shops.length === 0) return { status: 400, err: '店铺不存在' };
    const shop = shops[0] as shopType;
    return {
      id: shop.id,
      signature: shop.signature,
    };
  }

  public async removeShop(shopId) {
    const { app } = this;
    const shops = await app.mysql.select('shops', { where: { id: shopId } });
    if (shops.length === 0) return { status: 400, err: '店铺不存在' };
    await app.mysql.delete('shops', { id: shopId });
    return { message: '删除成功' };
  }
}
